package com.ktjy.ktmall.servlet;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ktjy.ktmall.entity.AjaxResult;
import com.ktjy.ktmall.entity.WxUser;
import com.ktjy.ktmall.service.WxUserService;
import com.ktjy.ktmall.service.impl.WxUserServiceImpl;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.stream.Collectors;

// 用于处理微信会员信息的修改操作。
@WebServlet(name = "WxUserServlet", urlPatterns = "/uni/wxUser/profile")
public class WxUserServlet extends HttpServlet {

    private WxUserService wxUserService;

    @Override
    public void init(ServletConfig config) throws ServletException {
        wxUserService = new WxUserServiceImpl();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1、创建out对象
        PrintWriter out = response.getWriter();
        // 2、获取从小程序端请求过来的参数
        // request.getReader()用于获取BufferedReader对象，用来读取从小程序请求过来的参数
        // 调用lines()方法可以将一个BufferedReader对象转换为一个Stream对象。
        // 再调用collect()以及Collectors.joining()将传递过来的请求参数使用逗号拼接成字符串
        String params = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
        // 将JSON字符串转换成JSONObject对象
        cn.hutool.json.JSONObject object = JSONUtil.parseObj(params);
        // 从JSONObject对象中获取key为opr所对应的值，再转换成String类型。
        String opr = object.get("opr", String.class);
        WxUser wxUser = object.get("wxUser", WxUser.class);
        AjaxResult result = null;
        if ("update".equals(opr)) {
            // 修改会员信息
            int i = wxUserService.updateWxUser(wxUser);
            if (i > 0) {
                result = AjaxResult.success("修改成功!", wxUser);
            } else {
                result = AjaxResult.error("修改失败!");
            }
        }
        out.print(JSON.toJSONString(result));
        out.flush();
        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
